﻿using Account.Api.Client;
using Blazored.LocalStorage;
using Cyss.Core;
using CyssBlazor.Shared.Infrastructure;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace CyssBlazor.WebAssembly.Infrastructure
{
    public class UserAuthStateProvider : IUserAuthStateProvider
    {
        private ILocalStorageService _localStorage;
        private IBlazorWorkContext _workContext;
        public UserAuthStateProvider(IBlazorWorkContext workContext, ILocalStorageService localStorage)
        {
            _localStorage = localStorage;
            _workContext = workContext;
        }


        public async Task<bool> GetAuthenticationStateAsync()
        {
            if (_workContext.User != null)
            {
                return true;
            }
            var savedToken = await _localStorage.GetItemAsync<string>("authToken");

            if (string.IsNullOrWhiteSpace(savedToken))
            {
                return false;
            }
            var apiResponse = await AccountClientFactory.User.TokenLogin(savedToken);
            if (apiResponse.IsSuccess == false)
            {
                return false;
            }
            if (apiResponse.IsSuccess && apiResponse.Data != null)
            {
                _workContext.User = new AuthenticationUser();
                _workContext.User.Id = apiResponse.Data.Id;
                _workContext.User.Name = apiResponse.Data.Name;
                _workContext.User.UserNo = apiResponse.Data.No;
                _workContext.Menus = apiResponse.Data.Menus.ToList();
                _workContext.UserRoles = apiResponse.Data.UserRoles.ToList();
                _workContext.Token = savedToken;
                _workContext.Permissions = apiResponse.Data.Permissions.ToList();
                _workContext.IsLogin = true;
            }
            return true;
        }

        public void LogUserOut()
        {

        }

        public void Login()
        {

        }
    }
}
